﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MinoSoft.sslpDataSetTableAdapters;

namespace MinoSoft
{
    public partial class FrmAgregarVenta : Form
    {

        public FrmAgregarVenta()
        {
            InitializeComponent();
        }


        private void FrmAgregarVenta_Load(object sender, EventArgs e)
        {
            dgvAgregarVenta.Rows.Insert(0, 1);
        }

        /// <summary>
        /// Evento cuando se presiona una tecla en el form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmAgregarVenta_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.Close();
            }
        }

        /// <summary>
        /// Metodo para autocompletar el ID de Articulo
        /// </summary>
        /// <returns></returns>
        public AutoCompleteStringCollection AutoCompleteIDArticulo()
        {
            AutoCompleteStringCollection str = new AutoCompleteStringCollection();
            ARTICULOSTableAdapter articulos = new ARTICULOSTableAdapter();
            sslpDataSet.ARTICULOSDataTable dt = articulos.GetData();

            foreach (DataRow row in dt.Rows)
                str.Add(row["IDARTICULO"].ToString());
            return str;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvAgregarVenta_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            TextBox tb = (TextBox)e.Control;
            if (dgvAgregarVenta.CurrentCell.ColumnIndex == 0)
            {
                
                if (tb != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    tb.AutoCompleteCustomSource = AutoCompleteIDArticulo();
                    tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }

            }
            else
                tb.AutoCompleteCustomSource = null;
            
            if (dgvAgregarVenta.CurrentCell.ColumnIndex == 3)
            {
                DataGridViewTextBoxEditingControl tbx =(DataGridViewTextBoxEditingControl)e.Control;
                tbx.KeyPress -= precio_KeyPress;
                tbx.KeyPress += new KeyPressEventHandler(precio_KeyPress);
            }

        }

        /// <summary>
        /// Evento para la columna precio
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void precio_KeyPress(object sender, KeyPressEventArgs e)
        {
            //Columna PRECIO
            if (dgvAgregarVenta.CurrentCell.ColumnIndex == 3)
            {
                updateTextImporte((DataGridViewTextBoxEditingControl)dgvAgregarVenta.EditingControl, e);
            }
        }
       
        private void updateTextImporte(DataGridViewTextBoxEditingControl dataGridViewTextBoxEditingControl, KeyPressEventArgs e)
        {            
            
            if (Char.IsNumber(e.KeyChar))
            {
                String text = dataGridViewTextBoxEditingControl.Text.Substring(0, dataGridViewTextBoxEditingControl.Text.Length);
                String aux = "";

                e.Handled = true;
                String str = new String(e.KeyChar, 1);

                aux = text.Substring(0, text.Length - 3);
                aux += text.Substring(text.Length - 2, 1);
                aux += "," + text.Substring(text.Length - 1, 1) + str;

                Double impo = Double.Parse(aux);

                dataGridViewTextBoxEditingControl.Text = "";
                dataGridViewTextBoxEditingControl.Text = String.Format("{0:0.00}", impo);

                dataGridViewTextBoxEditingControl.SelectionStart = dataGridViewTextBoxEditingControl.Text.Length;
            }
            else if (e.KeyChar == '\b')
            {
                String text = dataGridViewTextBoxEditingControl.Text.Substring(0, dataGridViewTextBoxEditingControl.Text.Length);
                String aux = "";
                e.Handled = true;

                if (text.Length < 4)
                {
                    aux = "0,00";
                }
                else
                {
                    aux = text.Substring(0, text.Length - 4);
                    aux += ",";
                    aux += text.Substring(text.Length - 4, 1);
                    aux += text.Substring(text.Length - 2, 1);
                }

                Double impo = Double.Parse(aux);
                dataGridViewTextBoxEditingControl.Text = "";

                if (impo.ToString().Equals("0"))
                    dataGridViewTextBoxEditingControl.Text = "0,00";
                else
                    dataGridViewTextBoxEditingControl.Text = String.Format("{0:0.00}", impo);

                dataGridViewTextBoxEditingControl.SelectionStart = dataGridViewTextBoxEditingControl.Text.Length;
            }
            else
                e.Handled = true;
        
        }

        /// <summary>
        /// Evento cuando se termina de editar una celda del datagrid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvAgregarVenta_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {        

            ///Manejo del total si la columna es cantidad o precio o descuento
            if (dgvAgregarVenta.CurrentCell.ColumnIndex == 2 || 
                dgvAgregarVenta.CurrentCell.ColumnIndex == 3 ||
                dgvAgregarVenta.CurrentCell.ColumnIndex == 4 )
            {
                if (dgvAgregarVenta.CurrentRow.Cells["PRECIO"].Value == null ||
                    "".Equals(dgvAgregarVenta.CurrentRow.Cells["PRECIO"].Value.ToString()))
                    dgvAgregarVenta.CurrentRow.Cells["PRECIO"].Value = 0;

                if (dgvAgregarVenta.CurrentRow.Cells["CANTIDAD"].Value == null ||
                    "".Equals(dgvAgregarVenta.CurrentRow.Cells["CANTIDAD"].Value.ToString()))
                    dgvAgregarVenta.CurrentRow.Cells["CANTIDAD"].Value = 0;

                if (dgvAgregarVenta.CurrentRow.Cells["DESCUENTO"].Value == null ||
                    "".Equals(dgvAgregarVenta.CurrentRow.Cells["DESCUENTO"].Value.ToString()))
                    dgvAgregarVenta.CurrentRow.Cells["DESCUENTO"].Value = 0;


                Decimal precioPorCantidad = (Decimal.Parse(dgvAgregarVenta.CurrentRow.Cells["PRECIO"].Value.ToString()) * Decimal.Parse(dgvAgregarVenta.CurrentRow.Cells["CANTIDAD"].Value.ToString()));
                Decimal descuento = precioPorCantidad * Decimal.Parse(dgvAgregarVenta.CurrentRow.Cells["DESCUENTO"].Value.ToString()) / 100;

                dgvAgregarVenta.Rows[e.RowIndex].Cells[5].Value = precioPorCantidad - descuento;

                //Recalculo la cantidad
                txtCantidad.Text = recalculoCantidad().ToString();

                //Recalculo total
                txtTotVta.Text = recalculoTotal().ToString().Equals("0") ? "0,00" : recalculoTotal().ToString();
            }          
        }

        private Decimal recalculoTotal()
        {
            Decimal total = 0;
            foreach (DataGridViewRow row in dgvAgregarVenta.Rows)
            {
                total += Decimal.Parse(row.Cells["TOTAL"].Value.ToString());
            }
            return total;
        }

        private int recalculoCantidad()
        {
            int cant = 0;
            foreach (DataGridViewRow row in dgvAgregarVenta.Rows)
            {
                cant += int.Parse(row.Cells["CANTIDAD"].Value.ToString());
            }
            return cant;
        }

        /// <summary>
        /// Evento cuando se presiona una tecla en el datagrid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvAgregarVenta_KeyPress(object sender, KeyPressEventArgs e)
        {
            //Para eliminar una fila Cuando se persiona 'Backspace'
            if (e.KeyChar == Convert.ToChar(Keys.Back) //Que sea la tecla Backspace
                && dgvAgregarVenta.CurrentCell.ColumnIndex != 3//Que no sea la columna de precios
                && dgvAgregarVenta.Rows.Count > 1)//Que haya mas de una fila
            {
                eliminarFila();
            }

            //Columna TOTAL
            if (dgvAgregarVenta.CurrentCell.ColumnIndex == 5)
            {
                if (dgvAgregarVenta.CurrentCell.RowIndex + 1 == dgvAgregarVenta.RowCount
                    && e.KeyChar == Convert.ToChar(Keys.Enter)
                    && filaCompleta())
                {   
                    dgvAgregarVenta.Rows.Add("", "", "0", "0,00", "0", "0,00");
                    dgvAgregarVenta.Rows[dgvAgregarVenta.RowCount - 1].Cells[0].Selected = true;
                }
            }
        }

        private void eliminarFila()
        {            
            //Primero consulto si desea eliminar el registro
            DialogResult res = Dialogos.YesNo("¿Está seguro que desea eliminar este artículo?", "Eliminar venta de articulo");

            if (DialogResult.Yes == res)
            {
                //Eliminar la fila
                dgvAgregarVenta.Rows.Remove(dgvAgregarVenta.Rows[dgvAgregarVenta.CurrentCell.RowIndex]);
                txtCantidad.Text = recalculoCantidad().ToString();
                txtTotVta.Text = recalculoTotal().ToString();
            }            
        }

        /// <summary>
        /// Verifica que la fila este completa con datos
        /// </summary>
        /// <returns></returns>
        private bool filaCompleta()
        {
            for (int i = 0; i < dgvAgregarVenta.Columns.Count; i++)
            {
                if (dgvAgregarVenta.CurrentRow.Cells[i].Value == null ||
                    dgvAgregarVenta.CurrentRow.Cells[i].Value.ToString() == "")
                    return false;
            }
            return true;
        }


        private void txtImpoPago_KeyPress(object sender, KeyPressEventArgs e)
        {
            updateTextImporte(txtImpoPago, e);
            
            //Si se presiona ENTER 
            if(e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                txtImpoPago.Enabled = false;
                btnGuardar.Enabled = true;
                btnGuardar.Focus();
                btnImprimir.Enabled = true;
            }

        }

        private void updateTextImporte(TextBox txtBox, KeyPressEventArgs e)
        {
            String text = txtBox.Text.Substring(0, txtBox.Text.Length);
            String aux = "";

            if (Char.IsNumber(e.KeyChar))
            {
                e.Handled = true;
                String str = new String(e.KeyChar, 1);

                aux = text.Substring(0, text.Length - 3);
                aux += text.Substring(text.Length - 2, 1);
                aux += "," + text.Substring(text.Length - 1, 1) + str;

                Double impo = Double.Parse(aux);

                txtBox.Text = "";
                txtBox.Text = String.Format("{0:0.00}", impo);

                txtBox.SelectionStart = txtBox.Text.Length;
            }
            else if (e.KeyChar == '\b')
            {
                e.Handled = true;

                if (text.Length < 4)
                {
                    aux = "0,00";
                }
                else
                {
                    aux = text.Substring(0, text.Length - 4);
                    aux += ",";
                    aux += text.Substring(text.Length - 4, 1);
                    aux += text.Substring(text.Length - 2, 1);
                }

                Double impo = Double.Parse(aux);
                txtBox.Text = "";

                if (impo.ToString().Equals("0"))
                    txtBox.Text = "0,00";
                else
                    txtBox.Text = String.Format("{0:0.00}", impo);

                txtBox.SelectionStart = txtBox.Text.Length;
            }
            else
                e.Handled = true;

        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            VENTASTableAdapter ventas = new VENTASTableAdapter();
            VENTASEXTTableAdapter ventasExt = new VENTASEXTTableAdapter();
            STOCKTableAdapter stock = new STOCKTableAdapter();
            ARTICULOSTableAdapter articulos = new ARTICULOSTableAdapter();

            try
            {
                //Obtengo nuevo id de venta y totales
                long idVenta = Secuenciador.getInstance().nextIDVenta();
                int cantTotal = int.Parse(txtCantidad.Text);
                Decimal total = Decimal.Parse(txtTotVta.Text);

                //Inserto registro de venta
                ventas.Insert(idVenta, DateTime.Now, txtObserv.Text, cantTotal, total);

                //Inserto los articulos vendidos en ventasExt
                foreach (DataGridViewRow row in dgvAgregarVenta.Rows)
                {
                    String idAarticulo = row.Cells["ARTICULO"].Value.ToString().ToUpper();
                    int cantidad = int.Parse(row.Cells["CANTIDAD"].Value.ToString());
                    Decimal importe = Decimal.Parse(row.Cells["PRECIO"].Value.ToString());
                    int descuento = int.Parse(row.Cells["DESCUENTO"].Value.ToString());

                    //insert en ventasExt
                    ventasExt.Insert(idVenta, DateTime.Now, idAarticulo, importe, cantidad, (byte)descuento);

                    //Inserto movimiento de stock
                    stock.Insert(Secuenciador.getInstance().nextIDStock(), DateTime.Now, idAarticulo, cantidad, 0);

                    //update de stock del articulo
                    articulos.VentaArticulo(cantidad, idAarticulo);
                }
            }
            catch (Exception ex)
            {
                Dialogos.error(ex.Message);
            }
            finally
            {
                this.Close();
            }
        }


        /// <summary>
        /// Evento para eliminar fila
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsEliminar_Click(object sender, EventArgs e)
        {
            //Si hay mas de 1 fila
            if (dgvAgregarVenta.Rows.Count > 1)
            {
                eliminarFila();
            }
        }

        private void txtImpoPago_TextChanged(object sender, EventArgs e)
        {
            Decimal totVta = Decimal.Parse(txtTotVta.Text);
            Decimal impoPago = Decimal.Parse(txtImpoPago.Text == "" ? "0,00" : txtImpoPago.Text);

            if(impoPago - totVta >= 0)
                txtVuelto.Text = Math.Abs(impoPago - totVta).ToString();
        }

        private void dgvAgregarVenta_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //Autocompletar
            if (dgvAgregarVenta.CurrentCell.ColumnIndex == 0)
            {
                dgvAgregarVenta.EndEdit();
                ARTICULOSTableAdapter articulos = new ARTICULOSTableAdapter();
                sslpDataSet.ARTICULOSDataTable dt = new sslpDataSet.ARTICULOSDataTable();

                articulos.FillByID(dt, dgvAgregarVenta.CurrentRow.Cells[0].Value.ToString().ToUpper());

                if (dt.Count == 1)
                    dgvAgregarVenta.CurrentRow.Cells["DESCRIPCION"].Value = dt[0].DESCRIPCION;
                else
                {
                    Dialogos.error("Articulo inexistente");
                    e.Cancel = true;
                    dgvAgregarVenta.BeginEdit(true);
                }
            }      


            //Valido stock disponible del articulo
            if (dgvAgregarVenta.CurrentCell.ColumnIndex == 2)
            {
                dgvAgregarVenta.EndEdit();
                int cantIngresada = int.Parse(dgvAgregarVenta.CurrentRow.Cells["CANTIDAD"].Value.ToString());
                int cantStock = 0;

                //Busco el articulo
                ARTICULOSTableAdapter articulos = new ARTICULOSTableAdapter();
                sslpDataSet.ARTICULOSDataTable dt = new sslpDataSet.ARTICULOSDataTable();

                articulos.FillByID(dt, dgvAgregarVenta.CurrentRow.Cells[0].Value.ToString().ToUpper());
                cantStock = dt[0].STOCK;

                if (cantIngresada > cantStock)
                {
                    Dialogos.error("No hay stock sufiente del articulo '" + dt[0].IDARTICULO + "'\nStock actual: " + cantStock);
                    e.Cancel = true;
                    dgvAgregarVenta.BeginEdit(true);
                }
                
            }
        }
       
    }
}
